package com.voxel.sense.infomsg.module.map.warn;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.amap.api.maps.model.Marker;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.example.com.common.app.BasePresenter;
import com.example.com.common.factory.data.DataSource;
import com.example.com.common.utils.L;
import com.example.com.common.utils.NetworkUtils;
import com.example.com.common.utils.TimeUtils;
import com.example.com.common.utils.ToastUtil;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.bean.InfoWindowSiteItemBean;
import com.voxel.sense.infomsg.data.bean.MakerInfoBean;
import com.voxel.sense.infomsg.data.bean.MultiItemBean;
import com.voxel.sense.infomsg.data.bean.RealDataBean;
import com.voxel.sense.infomsg.utils.GPSUtils;
import com.voxel.sense.infomsg.utils.marker.cluster.data.ClusterItem;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.model.api.response.FirmLatestOverDataEntity;
import cyy.example.com.facotry.model.api.response.StaffLocationInfoEntity;
import cyy.example.com.facotry.model.api.response.UnnormalFacilityEntity;
import cyy.example.com.facotry.model.api.response.WarningFirmEntity;
import cyy.example.com.facotry.net.RequestIdFactory;
import cyy.example.com.facotry.net.helper.FirmNetHelper;
import cyy.example.com.facotry.net.helper.NetHelper;

/**
 * 预警模块
 * Created by ChenYiYao on 2018/3/21.
 */

public class FirmWarnPresenter extends BasePresenter<FirmWarnContract.View> implements FirmWarnContract.Presenter,
        DataSource.Callback<BaseEntity> {

    private String mCurrentMarkId;//网络请求回来的数据id
    private HandlerThread mHandlerThread;
    private Handler mHandler;

    @Override
    public void start() {
        super.start();
        mHandlerThread = new HandlerThread("loadData");
        mHandlerThread.start();
        mHandler = new FirmWarnPresenter.DataHandle(mHandlerThread.getLooper());
    }

    @Override
    public void destroy() {
        super.destroy();
    }

    public FirmWarnPresenter(FirmWarnContract.View view) {
        super(view);
    }


    @Override
    public void doLoadWarningFirm() {
        mView.showLoading("");
        NetHelper.getWarningFirmInfo(this);
    }


    @Override
    public void doLoadMarkerInfo(Marker marker, String type) {
        ClusterItem data = (ClusterItem) marker.getObject();
        if (!NetworkUtils.isConnected()) {
            mView.showError(Factory.app().getString(R.string.network_unavailable));
        } else if (Constants.MARKER_TYPE_WARN_OVER_FIRM.equals(type)) { //超标数据
            //点击公司的marker消息公司的信息窗口
            WarningFirmEntity.OutOfLimitCompanyBean bean = (WarningFirmEntity.OutOfLimitCompanyBean) data.getObject();
            mCurrentMarkId = bean.getCompanyId();
            //请求网络
//            mView.showLoading("");
            NetHelper.getOverproofFirmDetails(bean.getCompanyId(), FirmWarnPresenter.this);

        } else if (Constants.MARKER_TYPE_WARN_FACILITY_FIRM.equals(type)) {
            //设备数据
            final WarningFirmEntity.UnusualCompanyBean bean = (WarningFirmEntity.UnusualCompanyBean) data.getObject();
//            mView.showLoading("");
            mCurrentMarkId = bean.getCompanyId();//记录当前id
            FirmNetHelper.getUnnormalFacilityInfo(mCurrentMarkId, FirmWarnPresenter.this);
        }
    }

    public void getItemClickInfo(String id){
        NetHelper.getOverproofFirmDetails(id, FirmWarnPresenter.this);
    }

    public void getComputeInfoById(String id, int type){
        //根据id获取公司名称
        NetHelper.getOverproofFirmDetail(id, type,FirmWarnPresenter.this);
    }

    int type = 0;
    int type1 = 0;
    @Override
    public void onDataLoaded(BaseEntity entity, int reqId) {
        if (mView == null)
            return;

        mView.dimissLoading();
        switch (reqId) {
            case RequestIdFactory.QUERY_USER_DETAIL://查询人员详情回调
                break;
            case RequestIdFactory.GET_FIRM_OVER_DATA://超标详情数据 最新

                FirmLatestOverDataEntity Overdata = (FirmLatestOverDataEntity) entity.getData();
                if (entity.isSuccess() && Overdata != null ) {
                    MakerInfoBean makerInfoBean = handlderOverData(Overdata);
                    mView.onShowInfoWindows(makerInfoBean);
                }
                break;
            case Constants.TYPE_WARM_OVER:
                FirmLatestOverDataEntity Overdata1 = (FirmLatestOverDataEntity) entity.getData();
//                if (entity.isSuccess() && Overdata != null && Overdata.getCompanyId().equals(mCurrentMarkId)) {
//                    MakerInfoBean makerInfoBean = handlderOverData(Overdata);
                    mView.onShowInfo(Overdata1, Constants.TYPE_WARM_OVER);
//                }
                break;
            case Constants.TYPE_WARM_DEVICE:
                FirmLatestOverDataEntity Overdata2 = (FirmLatestOverDataEntity) entity.getData();

                mView.onShowInfo(Overdata2, Constants.TYPE_WARM_DEVICE);
                break;
            case RequestIdFactory.GET_UNNORM_FACILITY://异常设备详情

                UnnormalFacilityEntity dataEntity = (UnnormalFacilityEntity) entity.getData();

                if (entity.isSuccess() && dataEntity.getCompanyId().equals(mCurrentMarkId)) {

                    MakerInfoBean makerInfoBean = handlerFacilityData(dataEntity);
                    mView.onShowInfoWindows(makerInfoBean);
                }else{
                    MakerInfoBean makerInfoBean = handlerFacilityData(dataEntity);
                    mView.onShowWindows(makerInfoBean);
                }
                break;
            case RequestIdFactory.GET_WARN_FIRM_LOCATION://获取超标的公司回调

                if (entity.isSuccess()) {
                    WarningFirmEntity firmEntity = (WarningFirmEntity) entity.getData();

                    List<WarningFirmEntity.OutOfLimitCompanyBean> outOfLimitDatas = firmEntity.getOutOfLimitCompany();
                    if (outOfLimitDatas != null && outOfLimitDatas.size() > 0) {
                        Message message = new Message();
                        message.what = DataHandle.COVER_OVER_DATA_COORD;
                        message.obj = outOfLimitDatas;
                        mHandler.sendMessage(message);
                    } else {

                            mView.noData(1);

                        ToastUtil.showToastLong(Factory.app(), "暂无超标数据");
                    }
                    List<WarningFirmEntity.UnusualCompanyBean> unusualCompany = firmEntity.getUnusualCompany();
                    if (unusualCompany != null && unusualCompany.size() > 0) {
                        Message message = new Message();
                        message.what = DataHandle.COVER_FACILITY_DATA_COORD;
                        message.obj = unusualCompany;
                        mHandler.sendMessage(message);
                    }
                    if (unusualCompany == null
                            && outOfLimitDatas == null && outOfLimitDatas.size() <= 0) {
                        ToastUtil.showToastLong(Factory.app(), "暂无预警数据");
                        type1 = 1;
                        if(type == 1) {
                            mView.noData(2);
                        }
                    }
                }
                break;
        }
    }

    @Override
    public void onDataNotAvailable(String strRes, int reqId) {
        if (mView == null)
            return;
        mView.dimissLoading();
        switch (reqId) {
            case RequestIdFactory.QUERY_USER_DETAIL://查询人员详情回调

                break;
            case RequestIdFactory.GET_FIRM_OVER_DATA://超标详情数据 最新

                break;
            case RequestIdFactory.GET_WARN_FIRM_LOCATION://获取超标的公司回调
                ToastUtil.showToastLong(Factory.app(), "获取超标公司数据失败");
                break;
        }
    }


    /**
     * 处理设备异常的详情弹窗数据
     */
    private MakerInfoBean handlerFacilityData(UnnormalFacilityEntity data) {
        List<MultiItemBean> listData = new ArrayList<>();//列表数据
        List<UnnormalFacilityEntity.SiteDataBean> siteDatas = data.getSiteData();
        //遍历站位
        if (siteDatas.size() > 0) {
            for (UnnormalFacilityEntity.SiteDataBean bean : siteDatas) {
                //添加站位的item
                InfoWindowSiteItemBean siteItemData = new InfoWindowSiteItemBean(bean.getSiteCode(), bean.getDatetime(), "");
                MultiItemBean<InfoWindowSiteItemBean> siteItemDataMultiItemBean = new MultiItemBean<>(siteItemData, Constants.DES_TYPE);
                listData.add(siteItemDataMultiItemBean);
                //添加数据item
                MultiItemBean<String> valueItem = new MultiItemBean<>(bean.getOnlineRate(), Constants.FACILITY_TYPE);
                listData.add(valueItem);

            }
        }
        MakerInfoBean infoBean = new MakerInfoBean(data.getCompanyName(), data.getAddress(), listData);
        return infoBean;
    }


    /**
     * 处理超标数据的详情弹窗数据
     */
    private MakerInfoBean handlderOverData(FirmLatestOverDataEntity data) {
        List<MultiItemBean> listData = new ArrayList<>();//列表数据
        List<FirmLatestOverDataEntity.SiteDataBean> siteDatas = data.getSiteData();
        if (siteDatas.size() > 0) {
            //遍历站位
            for (FirmLatestOverDataEntity.SiteDataBean siteData : siteDatas) {
                InfoWindowSiteItemBean siteItemData = new InfoWindowSiteItemBean();
                siteItemData.setSiteCode(siteData.getSiteCode());
                siteItemData.setWatchsiteName(siteData.getWatchsiteName());
                int i = 0;
                //遍历站位下的所有元素
                if (siteData.getSiteDataList().size() > 0) {
                    //站位信息作为单独的一列加入集合
                    MultiItemBean siteItem = new MultiItemBean(siteItemData, Constants.DES_TYPE);
                    listData.add(siteItem);
                    //两个元素作为一个item
                    RealDataBean[] realDataArry = new RealDataBean[2];
                    int ElementCount = 0;//元素个数
                    for (FirmLatestOverDataEntity.SiteDataBean.SiteDataListBean element : siteData.getSiteDataList()) {
                        //取余
                        int index = ElementCount % 2;
                        if (ElementCount != 0 && index == 0) {
                            realDataArry = new RealDataBean[2];
                        }
                        ElementCount++;
                        String realTime = element.getRealTime();
                        //暂时拿去第一个元素的时间，作为站位采集数据的时间
                        long l = TimeUtils.string2Millis(realTime, new SimpleDateFormat(Constants.REAL_DATA_TIME_FORMAT_TYPE));
                        if (i == 0 && !TextUtils.isEmpty(realTime)
                                && TextUtils.isDigitsOnly(realTime)) {
                            //转换时间格式
                            String time = TimeUtils.millis2String(l);
                            siteItemData.setDatetime(time);
                            i++;
                        }
                        RealDataBean realDataBean = new RealDataBean(element.getParamUnit(), element.getParamName(),
                                l, element.getParamValue(), element.getParamLimitValue());
                        realDataArry[index] = realDataBean;

                        //将数据添加到recycler列表集合中
                        if (index == 0) {
                            MultiItemBean Datatem = new MultiItemBean(realDataArry, Constants.OVER_DATA_TYPE);
                            listData.add(Datatem);
                        }
                    }
                }
            }
        }
        if (TextUtils.isEmpty(data.getCompanyName())) {
            return null;
        }
        MakerInfoBean infoBean = new MakerInfoBean(data.getCompanyName(), data.getAddress(), listData);
        return infoBean;

    }


    private void loadStaffIconUrl(final List<StaffLocationInfoEntity> datas) {
//        if (datas == null || datas.size() < 1) return;
//
//        final List<String> list = new ArrayList<>();
//        for (PeopleMarkerEntity.BodyBean data : datas) {
//            String taskTypeName = data.getPersonRoleType();
//            if (!list.contains(taskTypeName)) {
//                list.add(taskTypeName);
//            }
//        }
//        final int size = list.size();
//        final Map<String, Drawable> iconMap = new HashMap<>();
//        for (final String str : list) {
//            final String IconUrl = Factory.getFileUrl(str);
//            if (mView == null)
//                return;
//            ((Activity) mView).runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    LoadIcon(IconUrl, R.mipmap.marker_mission_icon, size, iconMap, str, DataHandle.REFRESH_STAFF_MARKER, datas);
//                }
//            });
//        }
    }

    /**
     * @param iconUrl 地址
     * @param ResId   资源id
     * @param count   总个数，用以判断是否全部加载完成
     * @param icon    装载数据的集体
     * @param key     map数据的key
     * @param msgId   发送消息的key
     * @param data    数据源
     */
    private void LoadIcon(final String iconUrl, final int ResId, final int count, final Map<String, Drawable> icon, final String key, final int msgId, final List data) {
        Glide.with(Factory.app())
                .asDrawable()
                .load(iconUrl) // 加载路径
                .apply(RequestOptions.centerCropTransform().error(ResId))
                .into(new SimpleTarget<Drawable>() {
                    /**
                     * 网络图片获取失败处理
                     */
                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {
                        super.onLoadFailed(errorDrawable);
                        icon.put(key, errorDrawable);
                        if (icon.size() == count) {
                            //所有的markerIcon已预加载完成,发送通知，加载marker
                            if (mView == null)
                                return;

                            mView.onLoadMakIconFinish(icon);
                            Message message = new Message();
                            message.obj = data;
                            message.what = msgId;
                            mHandler.sendMessage(message);
                        }
                    }

                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        icon.put(key, resource);
                        if (icon.size() == count) {
                            //所有的markerIcon已预加载完成,发送通知，加载marker
                            mView.onLoadMakIconFinish(icon);
                            Message message = new Message();
                            message.obj = data;
                            message.what = msgId;
                            mHandler.sendMessage(message);
                        }
                    }
                });
    }

    private void notifyViewAddMarker(final List datas, final String type, final Drawable drawable) {
        if (mView == null)
            return;
        ((Activity) mView).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                L.d("------onAddMarker------runOnUiThread");
//                mView.onAddMarker(datas, type, drawable);
                if (Constants.MARKER_TYPE_PEOPLE.equals(type)) {
                } else {
                    mView.onUpOverLimitDataMarker(datas);
                }
            }
        });
    }


    private class DataHandle extends Handler {
        static final int LOAD_STAFF_ICON = 0; //加载不同角色marker的icon
        static final int COVER_STAFF_COORD = 1; //转换staff数据
        static final int REFRESH_STAFF_MARKER = 3; //刷新人员坐标
        static final int COVER_OVER_DATA_COORD = 4; //抄表数据
        static final int COVER_FACILITY_DATA_COORD = 5;

        private DataHandle(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LOAD_STAFF_ICON:

                    break;
                case COVER_STAFF_COORD://人员数据转换坐标系

                    break;
                case REFRESH_STAFF_MARKER:
                    Object objStaff = msg.obj;
                    if (objStaff instanceof List) {
                        Drawable drawable = Factory.app().getResources().getDrawable(R.mipmap.marker_people_icon);
                        notifyViewAddMarker((List) objStaff, Constants.MARKER_TYPE_PEOPLE, drawable);
                    }
                    break;
                case COVER_FACILITY_DATA_COORD://公司超标数据转换坐标系
                    List<WarningFirmEntity.UnusualCompanyBean> facilityList = (List<WarningFirmEntity.UnusualCompanyBean>) msg.obj;
                    for (WarningFirmEntity.UnusualCompanyBean bean : facilityList) {
                        try {
                            String latitude = bean.getLatitude();
                            String longitude = bean.getLongitude();
                            double lat = Double.parseDouble(latitude);
                            double lon = Double.parseDouble(longitude);
                            double[] doubles = GPSUtils.bd09_To_Gcj02(lat, lon);
                            bean.setLatitude(doubles[0] + "");
                            bean.setLongitude(doubles[1] + "");
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                    }
                    mView.onUpFacilityAbnorDataMarker(facilityList);
                    break;
                case COVER_OVER_DATA_COORD://公司设备异常数据转换坐标系
                    List<WarningFirmEntity.OutOfLimitCompanyBean> list = (List<WarningFirmEntity.OutOfLimitCompanyBean>) msg.obj;
                    for (WarningFirmEntity.OutOfLimitCompanyBean bean : list) {
                        try {
                            String latitude = bean.getLatitude();
                            String longitude = bean.getLongitude();
                            double lat = Double.parseDouble(latitude);
                            double lon = Double.parseDouble(longitude);
                            double[] doubles = GPSUtils.bd09_To_Gcj02(lat, lon);
                            bean.setLatitude(doubles[0] + "");
                            bean.setLongitude(doubles[1] + "");
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                    }
                    mView.onUpOverLimitDataMarker(list);
                    break;
            }
        }

    }

}
